#include <stdio.h>
#include <pthread.h>
 
#define NTHREADS 10

void initialize_seed(int seed);
int read_random_number(void);
pthread_t test_thread(void);
void *thread_function(void *);

pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int  counter = 0, SEED = 15;

int main(void)
{
	int result;

	printf("INITIALIZING SEED: %d\n", SEED);
	initialize_seed(SEED);

	printf("READING FIRST VALUE\n");
	result = read_random_number();
	printf("FIRST VALUE: %d\n", result);

	printf("READING SECOND VALUE\n");
	result = read_random_number();
	printf("SECOND VALUE: %d\n", result);

	pthread_t thread;
	thread = test_thread();
	pthread_join(thread, NULL);
	//exit(0);

	printf("Final counter value: %d\n", counter);
	return 1;
}

void initialize_seed(int seed)
{
	FILE* LF;
	LF = fopen("/proc/lfprng", "w");
	fprintf(LF, "%d", seed);
	fclose(LF);
}

int read_random_number()
{
	FILE* LF;
	int random;
	LF = fopen("/proc/lfprng", "r");
	fscanf(LF, "%d", &random);
	fclose(LF);
	return random;
}

pthread_t test_thread()
{
	pthread_t thread;
	int success, test_value;
	test_value = 0;

	success = pthread_create(&thread,NULL,thread_function,&test_value);
	return thread;
}

void *thread_function(void *dummyPtr)
{
	int current_random_value;
	printf("Thread number %ld\n", pthread_self());
	pthread_mutex_lock( &mutex1 );

	//printf("Initializing thread seed: %d\n", SEED);
	//initialize_seed(SEED);

	printf("Reading random value\n");
	current_random_value = read_random_number();

	//++counter;
	printf("Thread number %ld receiving number: %d.\n", pthread_self(), current_random_value);
	pthread_mutex_unlock( &mutex1 );
}
